package com.qfedu.controller;

import com.github.wxpay.sdk.WXPay;
import com.qfedu.config.MyPayConfig;
import com.qfedu.fmmall.beans.Orders;
import com.qfedu.fmmall.vo.ResultStatus;
import com.qfedu.fmmall.vo.ResultVo;
import com.qfedu.service.OrderSubmitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin

public class OrderSubmitController {


    @Autowired
    private OrderSubmitService submitService;

    @PostMapping("/order/submit")
    public ResultVo submit(@RequestParam("cids")String cids,
            @RequestBody Orders orders){
        ResultVo resultVo = null;
        try {
            Map<String, String> orderInfo = submitService.addOrder(cids, orders);
            String orderId = orderInfo.get("orderId");
            if(orderId != null){
                //设置当前订单信息
                HashMap<String,String> data = new HashMap<>();
                data.put("body",orderInfo.get("productNames")); //商品描述
                data.put("out_trade_no",orderId);//使用当前用户订单的编号作为当前支付交易的交易号
                data.put("fee_type","CNY");//支付币中   人民币
                data.put("taotal_fee", orders.getActualAmount()*100+"");
                data.put("trade_type","NATIVE");//交易类型
                data.put("notify_url","pay/callback");//设置支付成功时回调方法

                //发送请求，获取响应
                //微信支付：申请支付链接
                WXPay wxPay = new WXPay(new MyPayConfig());
                Map<String,String> resq = wxPay.unifiedOrder(data);
                orderInfo.put("payUrl",resq.get("code_url"));

                resultVo = new ResultVo(ResultStatus.OK,"提交订单成功",orderInfo);
            }else{
                resultVo = new ResultVo(ResultStatus.NO,"订单提交失败",null);
            }

        }catch (Exception e){
            e.printStackTrace();
            resultVo = new ResultVo(ResultStatus.NO,"订单提交失败",null);
        }
        return resultVo;
    }
}
